<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form inline size="small" :model="from" ref="from" :label-position="labelPosition" label-width="100px">
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
                <el-form-item label="数据场：">
                  <UserSearchable v-model="from.dataFactoryId" :type="'datafieldList'" class="w_200">
                    <template #dropdownTitle>
                      <span>数据场名称</span>
                      <span>负责人</span>
                    </template>
                    <template v-slot:dropdown="{ item }">
                      <span>{{ item.name }}</span>
                      <span>{{ item.principal }}</span>
                    </template>
                  </UserSearchable>
                </el-form-item>
                <el-form-item label="用户：">
                  <UserSearchable v-model="from.userId" class="w_200"> </UserSearchable>
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="from.groupId" placeholder="请选择分组" clearable class="w_120">
                    <el-option :value="item.id" v-for="(item, index) in groupList" :key="index"
                      :label="item.groupName"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="标签">
                  <el-select multiple v-model="searchFrom.tagId" placeholder="请选择标签" clearable class="w_250">
                    <el-option :value="item.id" v-for="(item, index) in labelLists" :key="index"
                      :label="item.name"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间选择：" class="red_start">
                  <el-date-picker v-model="timeVal" value-format="yyyy-MM-dd" format="yyyy-MM-dd" :clearable="false"
                    type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    @change="onchangeTime">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
                <el-form-item>
                  <el-button class="mr10" size="small" icon="el-icon-search" type="primary" @click="search()">搜索</el-button>
                  <el-button class="mr10" size="small" icon="el-icon-refresh" @click="reset()">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <el-table border ref="table" v-loading="loading" :data="tableData.data" style="width: 100%" size="mini"
        highlight-current-row>
        <el-table-column prop="realName" label="姓名" min-width="100" />
        <el-table-column label="身份" prop="memberType" min-width="120">
          <template slot-scope="scope">
            <el-tag size="small" type="info" v-for="(item, index) in memberTypeList" :key="index" class="mr5"
              v-if="item.dictValue == scope.row.memberType">{{ item.dictLabel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataFactoryName" label="数据场" min-width="100" />
        <el-table-column prop="principal" label="负责人" min-width="100" />
        <el-table-column prop="sunCount" label="总手数" min-width="100" />
        <el-table-column prop="sunBrokerageFee" label="总佣金" min-width="100" />
        <el-table-column label="操作" min-width="130" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDetails(scope.row)">详情</el-button>
            <el-button type="text" size="small" @click="handleGenerate(scope.row)">生成佣金</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[15, 30, 45, 60]" :page-size="from.limit" :current-page="from.page"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
          @current-change="pageChange" />
      </div>
    </el-card>

    <!-- 详情 -->
    <el-dialog title="交易明细" :visible.sync="userVisible" width="1200px" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-table border :data="userData.data" highlight-current-row size="small">
        <el-table-column prop="uid" label="UID" min-width="100" />
        <!-- 更改字段 -->
        <el-table-column prop="userName" label="昵称" min-width="100" />
        <el-table-column prop="account" label="账户" min-width="100" />
        <el-table-column prop=" brokerageType" label="分佣方式" min-width="100">
          <template slot-scope="scope">
            <el-tag size="small" type="info" v-for="(item, index) in brokerageTypeList" :key="index" class="mr5"
              v-if="item.dictValue == scope.row.brokerageType">{{ item.dictLabel }}{{ scope.row.brokerageType == 3 ?
                `(${scope.row.percentReward * 100}%)` : "" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="commodityBrokerageVoList" label="合约" align="center" min-width="500">
          <template slot-scope="scope">
            <el-table border :data="scope.row.commodityBrokerageVoList">
              <el-table-column prop="commodityName" label="合约" min-width="100"></el-table-column>
              <el-table-column prop="commodityCount" label="手数" min-width="100"></el-table-column>
              <el-table-column prop="commodityBrokeragePrice" label="手续费/笔" min-width="150"></el-table-column>
              <el-table-column prop="commodityBrokerageFee" label="总手续费" min-width="150"></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="总手数" min-width="100" />
        <el-table-column prop="brokerageFee" label="总佣金" min-width="100">
          <template slot-scope="scope">
            <span>{{
              parseFloat(`${scope.row.brokerageFee}`)
                .toFixed(2)
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            }}</span>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[10, 20, 30, 40]" :page-size="detail.limit" :current-page="detail.page"
          layout="total, sizes, prev, pager, next, jumper" :total="userData.total" @size-change="handleUserSizeChange"
          @current-change="userPageChange" />
      </div>
      </el-card>
    </el-dialog>

    <el-dialog title="生成佣金" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="ruleForm" label-width="100px">
        <el-form-item label="总佣金：" prop="sunBrokerageFee">
          <el-input v-model="ruleForm.sunBrokerageFee"></el-input>
        </el-form-item>
        <el-form-item label="结算佣金：" prop="amount">
          <el-input v-model="ruleForm.amount" :disabled="true">{{ amount }}</el-input>
        </el-form-item>
        <el-form-item label="结算类型：" prop="brokerageSettlementTypeEnum">
          <span v-if="ruleForm.brokerageSettlementTypeEnum == 1">日结</span>
          <span v-if="ruleForm.brokerageSettlementTypeEnum == 2">周结</span>
          <span v-if="ruleForm.brokerageSettlementTypeEnum == 3">月结</span>
        </el-form-item>
        <el-form-item label="结算比率：" prop="brokerageFee">
          <el-input v-model="ruleForm.brokerageFee * 100" :disabled="true">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as roleApi from "@/api/role.js";
import { getDictData } from "@/api/transaction";
import {
  brokerageList,
  brokerageGetInfo,
  brokerageSave,
} from "@/api/financial";

import {
  tagListApi,
  groupListApi
} from '@/api/user'

import UserSearchable from "@/components/UserSearchable";

export default {
  name: "commissionManagement",
  components: {
    UserSearchable
  },
  data() {
    return {
      groupList: [],
      labelLists: [],
      searchFrom: {
        tagId: [],
      },


      memberTypeList: [],
      brokerageTypeList: [],
      labelPosition: "right",
      timeVal: [
        new Date(new Date().getTime() - 3600 * 1000 * 24 * 7),
        new Date(),
      ],
      from: {
        groupId: "",
        tagId: "",
        dataFactoryId: "",
        userId: "",
        beginTime: "",
        endTime: "",
        page: 1,
        limit: 15,
      },
      loading: false,
      tableData: {
        data: [],
        total: 0,
      },
      detail: {
        adminId: "",
        beginTime: "",
        endTime: "",
        page: 1,
        limit: 10,
      },
      userVisible: false,
      userData: {
        data: [],
        total: 0,
      },
      dialogVisible: false,
      ruleForm: {
        adminId: "",
        sunBrokerageFee: "",
        amount: "",
        brokerageSettlementTypeEnum: "",
        brokerageFee: "",
      },
    };
  },
  mounted() {
    this.getMemberTypeList();
    this.getlist();
    this.getDict();

    // 分组、标签
    this.groupLists();
    this.getTagList();
  },
  computed: {
    amount() {
      this.ruleForm.amount = (
        Number(this.ruleForm.sunBrokerageFee) *
        Number(this.ruleForm.brokerageFee)
      ).toFixed(2);
      return this.ruleForm.amount;
    },
  },
  methods: {
    // 分组列表
    groupLists() {
      groupListApi({ page: 1, limit: 9999 }).then(async (res) => {
        this.groupList = res.list;
      });
    },
    //标签列表
    getTagList() {
      tagListApi({ page: 1, limit: 9999 }).then((res) => {
        this.labelLists = res.list;
      });
    },
    getMemberTypeList() {
      roleApi.sysDictDataType("yj_admin_member_type").then((res) => {
        this.memberTypeList = res;
      });
    },
    // 具体日期
    onchangeTime(e) {
      console.log("🚀🚀🚀 ~ onchangeTime ~ e:", e);
      this.timeVal = e;
      this.getlist();
    },
    search() {
      console.log(this.from);
      this.from.page = 1;
      this.from.limit = 15;
      if (this.searchFrom.tagId.length > 0) {
        let tagId = this.searchFrom.tagId.join(",")
        this.from.tagId = tagId
      }
      this.getlist();
    },
    reset() {
      this.timeVal = [
        new Date(new Date().getTime() - 3600 * 1000 * 24 * 7),
        new Date(),
      ];
      this.from = {
        tagId: "",
        groupId: "",
        dataFactoryId: "",
        userId: "",
        beginTime: "",
        endTime: "",
        page: 1,
        limit: 15,
      };

      this.searchFrom.tagId = []
      this.getlist();
    },
    getlist() {
      console.log("🚀🚀🚀 ~ getlist ~ this.timeVal:", this.timeVal);
      this.loading = true;
      this.from.beginTime = this.timeVal[0]
        ? this.formatDate(this.timeVal[0])
        : "";
      this.from.endTime = this.timeVal[0]
        ? this.formatDate(this.timeVal[1])
        : "";
      brokerageList(this.from)
        .then((res) => {
          console.log(res);
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    handleGenerate(row) {
      console.log(row);
      this.ruleForm.adminId = row.adminId;
      this.ruleForm.sunBrokerageFee = row.sunBrokerageFee;
      this.ruleForm.brokerageSettlementTypeEnum =
        row.brokerageSettlementTypeEnum;
      this.ruleForm.brokerageFee = row.brokerageFee;
      this.dialogVisible = true;
    },
    close() {
      this.dialogVisible = false;
      this.ruleForm = {
        adminId: "",
        sunBrokerageFee: "",
        amount: "",
        brokerageSettlementTypeEnum: "",
        brokerageFee: "",
      };
    },
    submit() {
      let data = {
        adminId: this.ruleForm.adminId,
        amount: this.ruleForm.sunBrokerageFee,
        brokerageSettlementTypeEnum: this.ruleForm.brokerageSettlementTypeEnum,
        beginTime: this.from.beginTime,
        endTime: this.from.endTime,
      };
      brokerageSave(data)
        .then((res) => {
          console.log(res);
          this.close();
          this.$message.success("生成成功");
          this.getlist();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
    },
    pageChange(page) {
      this.from.page = page;
      this.getlist();
    },
    handleSizeChange(val) {
      this.from.limit = val;
      this.getlist();
    },
    handleDetails(row) {
      console.log(row);
      this.detail.adminId = row.adminId;
      (this.detail.beginTime = this.from.beginTime),
        (this.detail.endTime = this.from.endTime);
      this.detail.page = 1;
      this.detail.limit = 10;
      this.userData = {
        data: [],
        total: 0,
      };
      this.userVisible = true;
      this.getuserlist();
    },
    handleUserSizeChange(val) {
      this.detail.limit = val;
      this.getuserlist();
    },
    userPageChange(page) {
      this.detail.page = page;
      this.getuserlist();
    },
    getuserlist() {
      brokerageGetInfo(this.detail)
        .then((res) => {
          console.log("列表详情信息", res);
          this.userData.data = res.list;
          this.userData.total = res.total;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    formatDate(date) {
      if (!(date instanceof Date)) {
        date = new Date(date);
      }

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return `${year}-${month}-${day}`;
    },

    // 原来的 parseTime 方法现在调用 formatDate
    parseTime(time) {
      return this.formatDate(new Date(time));
    },
    // 字典数据
    getDict() {
      getDictData("yj_brokerage_type")
        .then((res) => {
          console.log("字典变量数据", res);
          this.brokerageTypeList = res;
        })
        .catch((res) => {
          console.log(res);
        });
    },
  },
};
</script>

<style scoped lang="scss">
.flex_wrap {
  display: flex;
  flex-wrap: wrap;
}

.w-60 {
  width: 60%;
}

.w_200 {
  width: 220px;
}

.w_120 {
  width: 120px;
}

.w_250 {
  width: 250px;
}

.red_start::after {
  content: "*";
  color: #ff4949;

  position: relative;
    bottom: 18px;
    left: 5px;
}
</style>
